#include "../header/common.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
#include <SDL/SDL_ttf.h>





#define N 1000
#define BUF_SIZ 4096




int click_button(SDL_Rect button,int x,int y)
{SDL_MouseMotionEvent mm;
  int i;
   
  
  if((x>button.x)&&(y>button.y)&&(x<button.x+button.w)&&(y<button.y+button.h))
  {
  return 1;
}
else 	    	
{	
  return 0;

}
}


void drawText(SDL_Surface* screen, SDL_Surface *back,TTF_Font* font, char* string,
			int x, int y, int fR, int fG, int fB)
{int high,weight;
	SDL_Color color = { fR, fG, fB };

	SDL_Surface* textSurface =  TTF_RenderText_Blended(font, string, color);
	weight=textSurface->w;
        high=textSurface->h;
	SDL_Rect textLocation = { x, y, weight,high };
	
SDL_BlitSurface(back,&textLocation,screen,&textLocation);
	SDL_BlitSurface(textSurface, NULL, screen, &textLocation);
	SDL_FreeSurface(textSurface);
}

void stringmalen(SDL_Surface *screen,TTF_Font *font,char string[N],int anfang,int ende,int x, int y)
{ int i;SDL_Color color = { 0, 255, 0 };
  char string2[80]={0},string3[2]={0};int weight=0, high=0;

 for(i=anfang;i<ende;i++)
       {
	 string2[strlen(string2)]=string[i];

       }

  for (i=0;i<ende-anfang;i++)
   {
     string3[0]=string2[i];
     string3[1]=0;
     SDL_Surface *textSurface =  TTF_RenderText_Blended(font, string3, color);
     weight=textSurface->w;     
high=textSurface->h;	
     SDL_Rect textLocation = { x, y, weight, high};
     SDL_FillRect(screen,&textLocation,SDL_MapRGB(screen->format,0,0,0));
     SDL_BlitSurface(textSurface, NULL, screen, &textLocation);
    
     SDL_FreeSurface(textSurface);x=x+weight;
   }  
       
}


void fertig(SDL_Surface *screen, TTF_Font *font,char string[N],int y2,int y,int e,int c,char name[50],int T[4])
{int laenge,i,l;
   char string2[N];

   l=strlen(name);
name[l]=':';  
 name[l+1]=' ';
   name[l+2]=0;
   string2[0]=0;
    if(!e)string2[0]=0;
   else strcat(string2,name);
    name[l]=0;
  strcat(string2,string);
  laenge=strlen(string2);
  
  if(e){send_request(c,string2);}
  SDL_Rect rect1 = { T[0],T[3],(screen->w)-T[0] , T[1]-(2*T[3])};
  SDL_Rect rect2 = { T[0], 0,(screen->w)-T[0] , T[1]-T[3]};
  SDL_Rect rect4 = { T[0], T[1],T[2] ,T[3] };
  SDL_Rect rect3 = { T[0],T[1]-(T[3]*2) ,(screen->w)-T[0],T[3] };
  SDL_BlitSurface(screen,&rect1,screen,&rect2);
  SDL_FillRect(screen,&rect4,SDL_MapRGB(screen->format,0,0,0));
  SDL_FillRect(screen,&rect3,SDL_MapRGB(screen->format,0,0,0));
  stringmalen(screen,font,string2,0,laenge, T[0],T[1]-2*T[3]);

   
}




int send_request( int sock,char string2[N])
{int laenge;
    char request[BUF_SIZ];
    
    snprintf(request, sizeof(request), "%s\n",string2);
    laenge=strlen(string2);
   

 
    
    if (send(sock, string2, strlen(request), 0) == -1)
    {
        perror("send() failed");
        return 1;
    }
    
    return 0;
}

int view_response( int sock)
{
    char response[BUF_SIZ];
    int bytes;

    bytes = recv(sock, response, sizeof(response), 0); 
    printf(" %s ", response);

    if (bytes < 0)
    {
        perror("recv() failed");
        return 1;
    }

    return 0;
}

int handle_client(SDL_Surface *screen, TTF_Font *font, int c,char name[50],int T[4])
{
  char buffer[BUF_SIZ];
  int bytes, laenge,i,x=0;
  char temp[20]="MUHH";
  
  bytes = recv(c, buffer, sizeof(buffer), 0);
  if(bytes>0)
    {
      fertig(screen,font,buffer,28,240,0,c,name,T);    
      for(i=0;i<4;i++)
	{
	  if(buffer[i]!=temp[i])
	    return 0;
        
	}
      if((bytes>0)&&(i==4))return 1;else return 0;
    }
} 
void ende(int sock)
{ char request[BUF_SIZ];
    
    snprintf(request, sizeof(request), "MUHH");
    
    if (send(sock, request, strlen(request), 0) == -1)
    {
        perror("send() failed");
        
    }
    
}



void einsortieren(int A[N],int weight,int pos,int T[4] )
{
 int i=0,b=1;
 A[1]=A[1]+1;
 for (i=A[1];i>pos;i--)
       {
	 A[i+1]=A[i];
       }
 A[pos+2]=weight;
 A[0]=T[0]+2;
 for(i=2;i<A[1]+2;i++)
       {
	 A[0]=A[0]+A[i];
       }

}

void bschreiben2(SDL_Surface *screen, Uint16 muh,TTF_Font *font,char string[N],int A[N],int S[2],int fR, int fG, int fB,int T[4])
{ char string1[2];
  int weight,i=0,rstring=0,astring=0,sanfang=0,sx,sy,sende=0;

 SDL_Color color = { fR, fG, fB };
 SDL_Surface *textSurface;
  

 string1[0]=(char)muh;
 string1[1]='\0';
  textSurface =  TTF_RenderText_Blended(font, string1, color);

  weight=textSurface->w;
 if(A[0]+weight<(T[2]+T[0])-2)
    {
   rstring=S[1];
 astring=A[1];
   
 for (i=astring+1;i>rstring;i--)
   {
     string[i]=string[i-1];
   
   }

 string[rstring]=(char)muh;
 string[(astring+1)]='\0';
 
	einsortieren(A,weight,S[1],T);
  sanfang=S[1];
  S[1]=S[1]+1; ;
  sende=A[1];
  sx=S[0];
  sy=T[1];

  stringmalen(screen,font,string,sanfang, sende, sx,sy );

  S[0]=S[0]+weight;}
  SDL_FreeSurface(textSurface);
}

void loeschen(SDL_Surface *screen, TTF_Font *font,char string[N], int A[N],int S[2],int r,int T[4])
{

  int i,x,y; 
  A[0]=A[0]-A[S[1]+1+r];if(r==0)S[0]=S[0]-A[S[1]+1];
  for (i=S[1]+r;i<A[1]+1+r;i++)
    {A[i+1]=A[i+2];string[i-1]=string[i];}
  A[1]=A[1]-1;if(r==0)S[1]=S[1]-1;
  x=S[0];
  y=T[1];
  SDL_Rect rect1= {S[0] , T[1],T[2]-(S[0]-T[0]),T[3] };
  SDL_FillRect(screen,&rect1,SDL_MapRGB(screen->format,0,0,0));
  stringmalen(screen,font,string,S[1],A[1],x,y);
  

}

void curserbewegen(char string[N],int A[N],int S[2],int r,int T[4])
{int i,m=T[0];
  
  if(r==-1)
    {
      for(i=2;i<A[1]+2;i++)
	{
	  m=m+A[i];
	  if(m==S[0])
	    {
	      S[0]=S[0]+(A[i]*r);
	      S[1]=S[1]+(1*r);
	      break;
	    }
	}

    }
  else
    { for(i=2;i<A[1]+2;i++)
	{
	  if(m==S[0])
	    {
	      S[0]=S[0]+(A[i]*r);
	      S[1]=S[1]+(1*r);
	      break;
	    }
	  else
	    {
	      m=m+A[i];
	    }
	}
    }
}

void curserclick(char string[N],int A[N], int S[2],int T[4],int x)
{
  int m=T[0],i;
  for(i=2;i<A[1]+2;i++)
    {
      m=m+A[i];
      if(m>x)
	{
	  S[0]=m-A[i];
	  S[1]=i-2;
	  break;
	}
      
    }
  if(m<x)
    {
      S[0]=m;
      S[1]=i-2;
    }

}


void chat(SDL_Surface *screen,int c,char name[50])
{
  SDL_Surface *temp, *background, *textfeld, *curser,*temp2;
  SDL_Rect back_dst,text_dst,curser_dst,text;
  SDL_Event event;
  TTF_Font *font;
  SDL_KeyboardEvent k_down;
  char string[N];
  int muh=0,muh1=0,done=0,x=28,y,i;
  int A[N]={0},S[2]={0},T[4];
  
  /* Bilder und andere Auflösungs äbhängige Werte werden geladen. */ 
 switch((screen->w))
    {
    case 640 :
      
      background=SDL_LoadBMP("image/640480/chat.bmp");
      curser=SDL_LoadBMP("image/640480/strich0.bmp");
      temp=SDL_LoadBMP("image/640480/temp.bmp"); 
      temp2=SDL_LoadBMP("image/640480/temp.bmp");  
      T[0]=16;
      T[1]=246;
      T[2]=490;
      T[3]=14;
         
      break;
      
    case 800 :
      
      background=SDL_LoadBMP("image/800600/chat.bmp");
      curser=SDL_LoadBMP("image/800600/strich0.bmp");
      temp=SDL_LoadBMP("image/800600/temp.bmp");
      temp2=SDL_LoadBMP("image/800600/temp.bmp");
      
      T[0]=20;
      T[1]=308;
      T[2]=613;
      T[3]=17;     
 break;
      
    case 1024 :
      
      background=SDL_LoadBMP("image/1024768/chat.bmp");
      curser=SDL_LoadBMP("image/1024768/strich0.bmp");
      temp=SDL_LoadBMP("image/1024768/temp.bmp");
      temp2=SDL_LoadBMP("image/1024768/temp.bmp");
      
	T[0]=25;
      T[1]=394;
      T[2]=784;
      T[3]=21;
      break;
    }
 
 /*Spielfeld wird zwischengepeichert*/
SDL_BlitSurface(screen,0,temp,0);

/* Chat wird gezeichnet*/
 x=T[0];
 S[0]=T[0]+2;
 font=TTF_OpenFont("arial.ttf",T[3]-2);
 back_dst.x=0;
 back_dst.y=0;
 back_dst.w=background->w;
 back_dst.h=background->h;
 SDL_Rect rect={T[0],T[1],T[2],T[3]};
 curser_dst.x=T[0]+2;
 curser_dst.y=T[1]+2;
 curser_dst.w=curser->w;
 curser_dst.h=curser->h;
 SDL_SetAlpha(temp2, SDL_SRCALPHA | SDL_RLEACCEL, 200);
 
 SDL_BlitSurface(temp2,NULL,screen,NULL);
 SDL_BlitSurface(background,0,screen,&back_dst);
 SDL_FillRect(screen,&rect,SDL_MapRGB(screen->format,0,0,0));
 SDL_BlitSurface(curser,0,screen,&curser_dst);
 
  SDL_Flip(screen);

  fcntl(c, F_SETFL, O_NONBLOCK);
  SDL_Delay(200);
  muh=SDL_EnableKeyRepeat(500,20);
  SDL_EnableUNICODE(1);

  /*Hauptschleife wird gestartet */  
while(!done)
    {      
      /*blinken des cursors*/
      if(muh1>1)
	{SDL_BlitSurface(curser,NULL,screen,&curser_dst);muh++;}
      else muh1++;
      if(muh>1)
	{SDL_FillRect(screen,&curser_dst,SDL_MapRGB(screen->format,0,0,0));
	  muh1=0;muh=0;}
      
      while (SDL_PollEvent(&event))
	{
	 switch(event.type)
	   {
	   case SDL_QUIT:
	     done = 1;ende(c);
	     break;
	   case SDL_KEYDOWN:
	     
	     /*Verarbeitung des Tastendruckes */
	     if((event.key.keysym.unicode>=32)&&(event.key.keysym.unicode<=126)|(event.key.keysym.unicode>=160)&&(event.key.keysym.unicode<=255))
	       {  bschreiben2(screen,event.key.keysym.unicode,font,string,A,S,0,255,0,T);}
	     SDL_FillRect(screen,&curser_dst,SDL_MapRGB(screen->format,0,0,0));
	     curser_dst.x=S[0];
	     switch(event.key.keysym.sym)
	       {
	       case SDLK_ESCAPE:
		 done=1;ende(c);
		 break;
		 
	       case SDLK_RETURN:
		 /* String wird gesendet, geblittet und das Textfeld wird wieder geleert.*/ 
		 fertig(screen,font,string,x,y,1,c,name,T);
		 for(i=2;i<A[1]+2;i++)
		   {A[i]=0;string[i-2]=0;}
		 A[0]=T[0]+2; A[1]=0;S[0]=T[0]+2; S[1]=0;
		 SDL_Rect rect3 = { T[0], T[1],(T[0]+T[2])-2 ,T[3] };		 
		 SDL_FillRect(screen,&rect3,SDL_MapRGB(screen->format,0,0,0));
		 curser_dst.x=S[0];
		 
		 
		 
		 break;
		 
	       case SDLK_BACKSPACE:
		 /*löschen*/
		 if(S[1]!=0)
		   {loeschen(screen,font,string, A, S,0,T);
		     curser_dst.x=S[0];}		 
		 break;
		 
	       case SDLK_DELETE:
		 if(S[1]<A[1]) 
		   {loeschen(screen,font,string, A, S,1,T);
		     curser_dst.x=S[0];}	 
		 printf("muh");
		 break;
		 /* Cursor wird bewegt*/
	       case SDLK_LEFT:
		 if(S[1]>0)
		   { 
		     curserbewegen(string,A,S,-1,T);
		     SDL_FillRect(screen,&curser_dst,SDL_MapRGB(screen->format,0,0,0));
		     curser_dst.x=S[0];
		   }break;
	       case SDLK_RIGHT:
		 if(S[1]<A[1])
		   {
		     curserbewegen(string,A,S,1,T);
		     SDL_FillRect(screen,&curser_dst,SDL_MapRGB(screen->format,0,0,0));
		     curser_dst.x=S[0];
		   }break;
	       }
	   }
	}
      /*Eingehende Strings werden verarbeitet */
      if(handle_client(screen,font,c,name,T))done=1;
      SDL_Flip(screen);
      SDL_Delay(100);
      
      
   }

  
/* SPielfeld wird wieder gezeichnet*/
  SDL_BlitSurface(temp,0,screen,0);
  SDL_Flip(screen);
  /*Surface werden freigegeben*/ 
  SDL_FreeSurface(background);
  SDL_FreeSurface(curser);
  SDL_FreeSurface(temp);
 

}

